<template>
  <div v-loading="loading" class="view-container">
    <el-row class="operation-btns" v-if="!(
        fileType == 'pdf' ||
        fileType == 'docx' ||
        fileType == 'doc' ||
        fileType == 'ppt' ||
        fileType == 'pptx' ||
        fileType == 'dwg' ||
        fileType == 'caj' ||
        fileType == 'ofd' ||
        fileType == 'url'
      )">
      <el-button type="primary" v-if="buttons.download" @click="handleDownload">下载</el-button>
      <el-button type="primary" v-if="buttons.screenshot" @click="handleScreenshot">截图</el-button>
      <el-button type="primary" v-if="buttons.print">打印</el-button>
      <el-button type="primary" v-if="buttons.delete">删除</el-button>
    </el-row>
    <!-- 预览文件的地方（用于渲染） -->
    <!-- pdf -->
    <div class="preview-wrapper" v-if="
        fileType == 'pdf' ||
        fileType == 'docx' ||
        fileType == 'doc' ||
        fileType == 'ppt' ||
        fileType == 'pptx' ||
        fileType == 'dwg' ||
        fileType == 'caj' ||
        fileType == 'ofd' ||
        fileType == 'url'
      ">
      <iframe @load="disableRightClick" ref="myIframe" :src="fileUrl" frameborder="0" :style="{ height: '100%', width: '100%' }"></iframe>
    </div>
    <!-- execl -->
    <div class="preview-wrapper" v-else-if="fileType == 'xls' || fileType == 'xlsx'">
      <ExcelPreview ref="excelPreview" :fileUrl="fileUrl" :fileType="fileType" :styles="{ height: 'calc(100vh - 56px)' }" />

      <!-- <LuckSheetExcel :fileName="fileInfo.fileName" :fileType="fileType" :fileUrl="fileUrl"></LuckSheetExcel> -->
    </div>
    <!-- ofd预览 -->
    <div class="preview-wrapper" v-else-if="fileType == 'ofd0'">
      <OfdPreview ref="OfdPreview" :url="fileUrl" />
    </div>

    <!-- 音频 -->
    <div class="preview-wrapper" v-else-if="isAudioFile('.' + fileType)">
      <audio controls :src="fileUrl"></audio>
    </div>
    <!-- 视频 -->
    <div class="preview-wrapper" v-else-if="isVideoFile('.' + fileType)" :src="fileUrl">
      <video width="100%" height="100%" controls :src="fileUrl"></video>
    </div>
    <!-- 图片 -->
    <div class="preview-wrapper img-box" v-else-if="isImgFile('.' + fileType)">
      <el-image style="width: 300px" :src="fileUrl" fit="contain" :preview-src-list="[fileUrl]">
      </el-image>
    </div>
    <!-- 文本类型 -->
    <Codemirror v-else-if="isTextFile('.' + fileType)" style="top: 130px" :initCodeValue="codeValue" :initEditorMode="fileType" :key="refreshCodemirrorKey"></Codemirror>
    <!-- 无法预览 -->
    <div v-else class="no-preview preview-wrapper hc-min-title">
      该文件类型无法在线预览，请下载后再打开
    </div>
  </div>
</template>


<script>
import
  {
    isImgFile,
    isVideoFile,
    isAudioFile,
    isTextFile,
    buildPDFPreviewUrl
  } from "../utils/index";
import
  {
    getOpenDownloadUrl,
    getWordPreviewUrl,
    getDwgToPdfUrl,
  } from "hc-core/api/common/attachment";
import { getDownloadUrl } from 'hc-core/api/common/filedata'
import request from "@/utils/request";
// import ExcelPreview from "hc-core/components/ExcelPreview.vue";
// import LuckSheetExcel from "hc-core/components/LuckSheetExcel";
import OfdPreview from "hc-core/components/OfdPreview";
import Codemirror from "./codemirror/index.vue";
import { Message } from "element-ui";
import ScreenShot from "js-web-screen-shot";

// 文件预览组件
export default {
  name: "filePreview",
  components: {
    ExcelPreview:() => import("hc-core/components/ExcelPreview.vue"),
    Codemirror,
    LuckSheetExcel:() => import("hc-core/components/LuckSheetExcel"),
    OfdPreview,
  },
  props: {
    //   文件信息
    fileInfo: {
      type: Object,
      default: () =>
      {
        return {};
      },
    },
    //是否显示按钮
    buttons: {
      type: Object,
      default: () =>
      {
        return {
          download: false,
          print: false,
          delete: false,
          screenshot: false,
        };
      },
    },
    //模块名称
    moduleName: {
      type: String,
      default: ""
    },
    //表单类型
    formType: {
      type: String,
      default: ""
    },
    //文件类型 zw 1
    attachmentType: {
      type: String | Number,
      default: ""
    },
    zwPreviewType: {
      type: String,
      default: ''
    },
    //通道ID
    channelId: "",
    //预览文件地址
    tragetUrl: {
      type: String,
      default: ''
    },
    //预览文件类型
    tragetFileType: {
      type: String,
      default: ''
    },
    //预览文件类型
    tragetFileName: {
      type: String,
      default: ''
    }
  },
  data()
  {
    return {
      //是否加载
      loading: false,
      //文件链接
      fileUrl: "",
      //文件类型
      fileType: "",
      //文件内容
      codeValue: "",
      //刷新key
      refreshCodemirrorKey: 0,
      //圈阅功能
      qyfile: window.HC_config.VUE_APP_QUAN_YUE || false,
    };
  },
  watch: {
    fileInfo: {
      handler()
      {
        this.render();
      },
      immediate: true,
    },
  },
  mounted()
  {
    this.initTargetFilePreview();
    console.log("_------失败----------")
    console.log(this.buttons);
    console.log("_------失败----------")
  },
  methods: {
    isImgFile,
    isAudioFile,
    isVideoFile,
    isTextFile,
    //截图
    handleScreenshot()
    {
      const that = this;
      new ScreenShot({
        completeCallback: (e) =>
        {
          console.log("成功返回======", e);
          // 创建 BroadcastChannel 实例
          const channel = new BroadcastChannel('notionPDF');
          // 向广播通道发送消息
          channel.postMessage({ channelId: that.channelId, base64: e.base64 });
          // 关闭频道
          channel.close()
          setTimeout(() =>
          {
            window.close();
          }, 1000)
        }
      });
    },
    //禁用右键
    disableRightClick()
    {
      const iframe = this.$refs.myIframe;
      const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
      
      iframeDoc.addEventListener('contextmenu', (e) => {
        e.preventDefault();
      });
    },
    //初始化文件预览
    initTargetFilePreview()
    {
      if (!this.tragetUrl)
      {
        return;
      }
      let fileUrl = "";
      if (["pdf", "docx", "doc", "dwg", "caj"].includes(this.tragetFileType))
      {
        let urlParams = {
          file: this.tragetUrl,
          download: this.buttons.download,
          filename: this.tragetFileName || "",
          qyfile: this.qyfile,
          print: this.buttons.print,
          presentationMode: false,
        };
        fileUrl = buildPDFPreviewUrl(urlParams);
      }
      console.log("初始化文件预览", fileUrl);
      this.fileType = this.tragetFileType;
      this.fileUrl = fileUrl;
    },
    //渲染
    render()
    {
      if (this.tragetUrl)
      {
        return;
      }
      if (!this.fileInfo)
      {
        Message.info("文件预览失败！文件数据异常。!");
        return;
      }
      this.fileType = this.fileInfo.fileType;
      if (!this.fileType) 
      {
        this.fileType = this.getFileTypeByFileName(this.fileInfo.fileName);
        if (!this.fileType) 
        {
          Message.info("文件预览失败！文件类型数据异常。!");
          return;
        }
      }
      this.fileType = this.fileType.toLowerCase();

      let fileUrl = this.formatFileUrl(this.fileInfo);
      if (["pdf", "docx", "doc", "dwg", "caj"].includes(this.fileType))
      {
        let urlParams = {
          file: fileUrl,
          download: this.buttons.download,
          filename: this.fileInfo.fileName || "",
          qyfile: this.qyfile,
          print: this.buttons.print,
          presentationMode: false,
          type: this.fileInfo.type,
          moduleName: this.fileInfo.moduleName,
          unid: this.fileInfo.relationUnid,
          fileUnid: this.fileInfo.unid,
          formType: this.formType,
        };
        fileUrl = buildPDFPreviewUrl(urlParams);
      } else if (this.fileType == "pptx" || this.fileType == "ppt")
      {
        fileUrl = `/pptx-js/index.html?file=${encodeURIComponent(fileUrl)}`;
      } else if (this.fileType == "ofd")
      {
        fileUrl = `/zxfw/ofdview.html?file=${this.fileInfo.unid}&watermark=false`
      } else if (this.fileType == 'url')
      {
        fileUrl = this.fileInfo.filePath + '&isPreview=' + true
      }

      console.log("文件类型", this.fileType)
      console.log("预览地址", fileUrl)
      this.fileUrl = fileUrl;
      if (isTextFile(`.${this.fileType}`))
      {
        this.downloadText();
      }

      console.log(fileUrl);
      if (['et'].includes(this.fileType))
      {
        try
        {
          viewExcelWithAttachment(
            fileUrl,
            this.fileInfo.unid,
            ""
          )
        } catch (err)
        {
          console.error("【et文件预览异常】", err);
          Message.info("该文件不支持在线预览!")
        }
      }
    },
    //通过文件名称获取文件类型
    getFileTypeByFileName(P_FileName)
    {
      let fileType = "";
      const matches = /\.([^.]+)$/.exec(P_FileName);
      if (matches)
      {
        fileType = matches ? matches[1] : "";
      }
      return fileType.toLowerCase();
    },
    //格式文件链接
    formatFileUrl(P_Item)
    {
      console.log("格式文件链接=====================", P_Item);
      if (
        P_Item.fileType == "docx" ||
        P_Item.fileType == "doc" ||
        P_Item.fileType == "caj" ||
        this.fileType == 'docx' ||
        this.fileType == 'doc'
      )
      {
        if (this.zwPreviewType == 'contract' && this.moduleName == 'fwgl')
        {
          let base_url = localStorage.getItem("local_server_ip") || window.HC_config.VUE_APP_BASE_API || process.env.VUE_APP_BASE_API;
          let url = base_url + "/sign/contract/showFile/?unid=" + P_Item.parentUnid + "#download=0"
          return url
        }
        else
        {
          return getWordPreviewUrl(P_Item.unid);
        }
      } else if (P_Item.fileType == "dwg")
      {
        return getDwgToPdfUrl(P_Item.unid);
      }
      if (this.moduleName == 'fwgl' && this.type == 'zw')
      {
        return getDownloadUrl(P_Item.parentUnid)
      }
      return getOpenDownloadUrl(P_Item.unid);
    },
    //文件下载
    handleDownload()
    {
      let requestParams = {
        url: getOpenDownloadUrl(this.fileInfo.unid),
        method: "get",
        responseType: "blob",
      };

      let fileName = this.fileInfo.fileName;
      //执行请求
      request(requestParams).then((res) =>
      {
        if (res instanceof Blob)
        {
          this.download(res, fileName);
        } else if (res.data instanceof Blob)
        {
          this.download(res.data, fileName);
        }
      });
    },
    //下载
    download(data, fileName)
    {
      if (!data)
      {
        return;
      }
      let url = window.URL.createObjectURL(new Blob([data]));
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    //对于text文件 下载
    downloadText()
    {
      let requestParams = {
        url: getOpenDownloadUrl(this.fileInfo.unid),
        method: "get",
        responseType: "blob",
      };
      //执行请求
      request(requestParams).then((res) =>
      {
        let data;
        if (res instanceof Blob)
        {
          data = res;
        } else if (res.data instanceof Blob)
        {
          data = res.data;
        }
        if (data)
        {
          //创建Blob对象
          let blob = new Blob([data], { type: "text/plain;charset=utf-8" });
          let tempFile = new File([blob], "test.text", { type: blob.type });
          let reader = new FileReader(); // 读取TXT起重要作用的
          reader.readAsText(tempFile, "UTF-8");
          ///读取文件里面的内容返回
          let self = this;
          reader.onload = function (event)
          {
            console.log("下载结果", event);
            self.codeValue = event.target.result;
            self.refreshCodemirrorKey++;
          };
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.view-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
}

.preview-wrapper {
  flex: 1;
}

.preview-box {
  display: flex;
  align-items: center;
  justify-content: center;
}

.img-box {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.no-preview {
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
}

.operation-btns {
  padding: 10px 10px;
}
</style>